//
//  VoiceChatModule.m
//  eWeiXin
//
//  Created by chen wenhao on 14-6-24.
//  Copyright (c) 2014年 chen wenhao. All rights reserved.
//

#import "VoiceChatModule.h"

@implementation VoiceChatModule

static VoiceChatModule* instance = nil;


+ (VoiceChatModule*)getInstance
{
    @synchronized(self)
    {
        if (instance==nil)
        {
            instance = [[VoiceChatModule alloc] init];
        }
    }
    return instance;
}

- (id)init{
    self = [super init];
    if (self) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:) name:UIDeviceProximityStateDidChangeNotification object:nil];
        
    }
    return self;
}

- (AVAudioRecorder *)getAVAudioRecorder
{
    return recorder;
}

//新增api,获取录音权限. 返回值,YES为无拒绝,NO为拒绝录音.
- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        bCanRecord = NO;
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                } else {
                    bCanRecord = NO;
                }
            }];
        }
    }
    
    return bCanRecord;
}


- (int)startRecord:(NSString *)path
{
    //判断有没有权限
    if (![self canRecord]) {
        return -2;
    }
    isCancel = NO;
    recordPath = path;
    
    NSDictionary *settings = [[NSDictionary alloc] initWithObjectsAndKeys:
                                   [NSNumber numberWithFloat: 8000.0],AVSampleRateKey, //采样率
                                   [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
                                   [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,//采样位数 默认 16
                                   [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,//通道的数目
                                   [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,//大端还是小端 是内存的组织方式
                                   [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,//采样信号是整数还是浮点数
                                   [NSNumber numberWithInt: AVAudioQualityMedium],AVEncoderAudioQualityKey,//音频编码质量
                                   nil];
    NSURL *pathURL=[NSURL fileURLWithPath:path];
    NSError *error=nil;
    recorder = [[AVAudioRecorder alloc] initWithURL:pathURL settings:settings error:&error];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    
    [recorder prepareToRecord];
    
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];

    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
	AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
    [recorder record];
    
    [self startTimer];
    
    return 0;
}

- (void)stopRecord
{
    if (recorder.isRecording)
    {
        [recorder stop];
    }
    
}

- (void)cancelRecord
{
    isCancel = YES;
    [self stopRecord];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:recordPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:recordPath error:nil];
    }
}


#pragma mark - 启动定时器
- (void)startTimer{
    timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(updateMeters) userInfo:nil repeats:YES];
}

#pragma mark - 停止定时器
- (void)stopTimer{
    if (timer && timer.isValid){
        [timer invalidate];
        timer = nil;
    }
}

#pragma mark - 更新音频峰值
- (void)updateMeters{
    
    double volume = [self getMICVolume];
    
    [NSNotificationCenter postMICVolumeChangeNotification:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:volume],@"volume", nil]];
    
}
#pragma mark - AVAudioRecorder Delegate Methods
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    NSLog(@"录音停止");
    
    [self stopTimer];
    
    if (isCancel) {
        //reason,1为取消录音，2为录音正常结束，3为录音非正常结束
        [NSNotificationCenter postAudioRecorderDidFinishNotification:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1],@"reason",nil]];
    }else {
        float length = [self getAudioLength:recordPath];
        
        [NSNotificationCenter postAudioRecorderDidFinishNotification:[NSDictionary dictionaryWithObjectsAndKeys:recordPath,@"path", [NSString stringWithFormat:@"%d",(int)length],@"length",[NSNumber numberWithInt:2],@"reason",nil]];
    }
    
    
    
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
    NSLog(@"audioRecorderEncodeErrorDidOccur");
}

- (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder withOptions:(NSUInteger)flags
{
    NSLog(@"audioRecorderEndInterruption");
}




- (void)startPlayAudio:(NSString *)path
{
    audioPath = path;
    if (player.playing) {
        [player stop];
        //发音频结束播放通知
        [NSNotificationCenter postAudioPlayDidFinishNotification];
    }
    NSURL *url = [NSURL fileURLWithPath:path];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSLog(@"音频不存在");
        return;
    }
    
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    player.delegate = self;
    [player play];
}

- (void)stopPlayAudio
{
    if (player.playing) {
        [player stop];
        //发音频结束播放通知
        [NSNotificationCenter postAudioPlayDidFinishNotification];
        [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
    }
}

#pragma mark - 处理近距离监听触发事件
-(void)sensorStateChange:(NSNotificationCenter *)notification;
{
    //如果此时手机靠近面部放在耳朵旁，那么声音将通过听筒输出，并将屏幕变暗（省电啊）
    if ([[UIDevice currentDevice] proximityState] == YES)//黑屏
    {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        
    }
    else//没黑屏幕
    {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        if (!player.playing) {//没有播放了，也没有在黑屏状态下，就可以把距离传感器关了
            [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
        }
    }
}

#pragma mark - AVAudioPlayer Delegate Methods
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"audioPlayerDidFinishPlaying");
    [NSNotificationCenter postAudioPlayDidFinishNotification];
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];

}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    NSLog(@"audioPlayerDecodeErrorDidOccur");
    [NSNotificationCenter postAudioPlayDidFinishNotification];
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags
{
    NSLog(@"audioPlayerEndInterruption");
}

- (double)getMICVolume
{
    if (recorder.isRecording){
        //更新峰值
        [recorder updateMeters];
        double peak = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
        
        return peak;
    }
    
    return 0;
}

- (float)getAudioLength:(NSString *)path
{
    AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:path] options:nil];
    
    CMTime audioDuration = audioAsset.duration;
    
    float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
    
    return audioDurationSeconds;

}
@end
